import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:magma/heartbeat/helpers/magma_loading.dart';
import 'package:magma/heartbeat/helpers/magma_tap.dart';
import 'package:magma/heartbeat/helpers/magma_url.dart';
import 'package:mobkit_dashed_border/mobkit_dashed_border.dart';
import 'package:path_provider/path_provider.dart';
import 'package:qlevar_router/qlevar_router.dart';
import 'package:stacked/stacked.dart';
import 'package:video_thumbnail/video_thumbnail.dart';
import '../../heartbeat/helpers/magma_constant.dart';
import '../../heartbeat/helpers/magma_text_style.dart';
import '../../heartbeat/helpers/magma_color.dart';
import '../../heartbeat/helpers/magma_toast.dart';
import '../../heartbeat/parts/login_required_dialog.dart';
import '../../comms_link/app_state.dart';
import '../../heartbeat/blueprint/user_model.dart';
import '../../heartbeat/blueprint/dynamic_model.dart';

/// 发布动态页面视图模型
class PublishDynamicNavigatorViewModel extends BaseViewModel {
  late PageController pageController;

  ContentType _selectedCategory = ContentType.image;
  ContentType get selectedCategory => _selectedCategory;

  final TextEditingController titleInput = TextEditingController();
  final TextEditingController descriptionInput = TextEditingController();

  String? _resourceLocation;
  String? get resourceLocation => _resourceLocation;

  String? _thumbnailLocation;
  String? get thumbnailLocation => _thumbnailLocation;

  /// 获取当前用户
  UserModel? get currentUser => appState.userStore.currentUser;

  /// 检查是否已登录
  bool get isLoggedIn => appState.userStore.isLoggedIn;

  /// 初始化
  void init() {
    pageController = PageController(initialPage: 0);
  }

  /// 切换类型
  void switchCategory(ContentType type) {
    _selectedCategory = type;
    _resourceLocation = null;
    _thumbnailLocation = null;

    // 切换到对应页面
    final targetPage = type == ContentType.image ? 0 : 1;
    pageController.animateToPage(
      targetPage,
      duration: const Duration(milliseconds: 300),
      curve: Curves.easeInOut,
    );

    notifyListeners();
  }

  /// 页面切换回调
  void onPageChanged(int index) {
    _selectedCategory = index == 0 ? ContentType.image : ContentType.video;
    _resourceLocation = null;
    _thumbnailLocation = null;
    notifyListeners();
  }

  /// 选择媒体资源
  Future<void> selectMediaResource(BuildContext context) async {
    try {
      final List<AssetEntity>? result = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: 1,
          requestType:
              _selectedCategory == ContentType.image
                  ? RequestType.image
                  : RequestType.video,
          pickerTheme: ThemeData.dark().copyWith(
            colorScheme: ColorScheme.dark(
              primary: MagmaColor.purple,
              surface: MagmaColor.black,
              onSurface: MagmaColor.white,
            ),
            appBarTheme: AppBarTheme(
              backgroundColor: MagmaColor.black,
              foregroundColor: MagmaColor.white,
            ),
            scaffoldBackgroundColor: MagmaColor.black,
            textButtonTheme: TextButtonThemeData(
              style: TextButton.styleFrom(foregroundColor: MagmaColor.purple),
            ),
          ),
          textDelegate: const EnglishAssetPickerTextDelegate(),
        ),
      );

      if (result != null && result.isNotEmpty) {
        await _handleSelectedMedia(result.first);
      }
    } catch (e) {
      // 打印错误日志
      print('选择媒体资源错误: $e');
      setError(e.toString());
      // 显示错误提示
      if (context.mounted) {
        MagmaToast.error(context, title: '选择失败: ${e.toString()}');
      }
    }
  }

  /// 处理选中的媒体文件
  Future<void> _handleSelectedMedia(AssetEntity mediaAsset) async {
    try {
      setBusy(true);

      // 获取应用目录
      final directory = await getApplicationDocumentsDirectory();
      final timestamp = DateTime.now().millisecondsSinceEpoch;

      // 获取文件
      final file = await mediaAsset.file;
      if (file == null) {
        setError('无法获取文件');
        return;
      }

      if (_selectedCategory == ContentType.image) {
        // 处理图片
        final imageName = 'image_$timestamp.jpg';
        final savedPath = '${directory.path}/$imageName';
        final bytes = await file.readAsBytes();
        final imageFile = File(savedPath);
        await imageFile.writeAsBytes(bytes);

        _resourceLocation = savedPath;
        _thumbnailLocation = null;
      } else {
        // 处理视频
        final videoName = 'video_$timestamp.mp4';
        final savedVideoPath = '${directory.path}/$videoName';
        final bytes = await file.readAsBytes();
        final videoFile = File(savedVideoPath);
        await videoFile.writeAsBytes(bytes);

        // 生成视频缩略图
        final thumbnailPath = await VideoThumbnail.thumbnailFile(
          video: savedVideoPath,
          thumbnailPath: directory.path,
          imageFormat: ImageFormat.JPEG,
          maxHeight: 200,
          quality: 75,
        );

        _resourceLocation = savedVideoPath;
        _thumbnailLocation = thumbnailPath;
      }

      notifyListeners();
    } catch (e) {
      setError(e.toString());
    } finally {
      setBusy(false);
    }
  }

  /// 发布动态
  Future<bool> releaseContent() async {
    if (!isLoggedIn) return false;

    if (titleInput.text.trim().isEmpty) {
      setError('Title cannot be empty');
      return false;
    }

    if (descriptionInput.text.trim().isEmpty) {
      setError('Description cannot be empty');
      return false;
    }

    if (_resourceLocation == null) {
      setError(
        'Please select a ${_selectedCategory == ContentType.image ? 'picture' : 'video'}',
      );
      return false;
    }

    final result = await appState.contentBroadcaster.broadcastContent(
      userId: currentUser!.id,
      title: titleInput.text.trim(),
      content: descriptionInput.text.trim(),
      type: _selectedCategory,
      imagePath:
          _selectedCategory == ContentType.image ? _resourceLocation : null,
      videoPath:
          _selectedCategory == ContentType.video ? _resourceLocation : null,
      coverImagePath:
          _selectedCategory == ContentType.video ? _thumbnailLocation : null,
    );

    return result;
  }

  @override
  void dispose() {
    titleInput.dispose();
    descriptionInput.dispose();
    pageController.dispose();
    super.dispose();
  }
}

/// 发布动态页面
class PublishDynamic extends StatelessWidget {
  const PublishDynamic({super.key});

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<PublishDynamicNavigatorViewModel>.reactive(
      viewModelBuilder: () => PublishDynamicNavigatorViewModel(),
      onViewModelReady: (viewModel) => viewModel.init(),
      builder: (context, viewModel, child) {
        return Scaffold(
          body: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(MagmaConstant.background),
                fit: BoxFit.cover,
              ),
            ),
            child: SafeArea(
              child: Column(
                children: [
                  // 标题栏
                  _constructHeader(context),

                  SizedBox(height: 20.h),

                  // 类型切换 - 在 PageView 外面
                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 20.w),
                    child: _assembleTypeSelector(viewModel),
                  ),

                  SizedBox(height: 24.h),

                  // 内容区域 - 使用 PageView
                  Expanded(
                    child: PageView(
                      controller: viewModel.pageController,
                      onPageChanged: viewModel.onPageChanged,
                      children: [
                        // 图片页面
                        _buildContentPage(
                          context,
                          viewModel,
                          ContentType.image,
                        ),
                        // 视频页面
                        _buildContentPage(
                          context,
                          viewModel,
                          ContentType.video,
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  /// 构建内容页面
  Widget _buildContentPage(
    BuildContext context,
    PublishDynamicNavigatorViewModel viewModel,
    ContentType type,
  ) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题
          Text('title').blackHanSans(
            fontSize: 18.sp,
            color: MagmaColor.white,
            fontWeight: FontWeight.w700,
          ),

          SizedBox(height: 12.h),

          // 标题输入框
          _constructTitleInput(viewModel),

          SizedBox(height: 20.h),

          // 简介
          Text('Introduction').blackHanSans(
            fontSize: 18.sp,
            color: MagmaColor.white,
            fontWeight: FontWeight.w700,
          ),

          SizedBox(height: 12.h),

          // 简介输入框
          _constructDescriptionInput(viewModel),

          SizedBox(height: 20.h),

          // 图片/视频
          Text(type == ContentType.image ? 'picture' : 'video').blackHanSans(
            fontSize: 18.sp,
            color: MagmaColor.white,
            fontWeight: FontWeight.w700,
          ),

          SizedBox(height: 12.h),

          // 选择媒体
          _assemblePictureSelector(context, viewModel),

          Spacer(),

          // 发布按钮
          _constructReleaseButton(context, viewModel),

          SizedBox(height: 12.h),

          // EULA 链接
          _assembleEulaLink(),

          SizedBox(height: 20.h),
        ],
      ),
    );
  }

  /// 构建标题栏
  Widget _constructHeader(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
      child: Row(
        children: [
          MagmaTap(
            onTap: () => QR.back(),
            child: Image.asset(
              MagmaConstant.back,
              width: 24.w,
              height: 24.w,
              color: MagmaColor.white,
            ),
          ),
          Expanded(
            child: Text('release', textAlign: TextAlign.center).blackHanSans(
              fontSize: 24.sp,
              color: MagmaColor.white,
              fontWeight: FontWeight.w700,
            ),
          ),
          SizedBox(width: 24.w),
        ],
      ),
    );
  }

  /// 组装类型选择器
  Widget _assembleTypeSelector(PublishDynamicNavigatorViewModel viewModel) {
    return Container(
      height: 56.h,
      decoration: BoxDecoration(
        color: MagmaColor.white.withOpacity(0),
        borderRadius: BorderRadius.circular(28.r),
        border: Border.all(color: MagmaColor.purple, width: 1.w),
      ),
      child: Row(
        children: [
          // Picture 选项
          Expanded(
            child: GestureDetector(
              onTap: () => viewModel.switchCategory(ContentType.image),
              child: Container(
                height: 56.h,
                decoration: BoxDecoration(
                  color:
                      viewModel.selectedCategory == ContentType.image
                          ? MagmaColor.purple
                          : Colors.transparent,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(28.r),
                    bottomLeft: Radius.circular(28.r),
                    topRight:
                        viewModel.selectedCategory == ContentType.image
                            ? Radius.circular(28.r)
                            : Radius.zero,
                    bottomRight:
                        viewModel.selectedCategory == ContentType.image
                            ? Radius.circular(28.r)
                            : Radius.zero,
                  ),
                ),
                child: Center(
                  child: Text('Picture').blackHanSans(
                    fontSize: 20.sp,
                    color:
                        viewModel.selectedCategory == ContentType.image
                            ? MagmaColor.black
                            : MagmaColor.white,
                    fontWeight: FontWeight.w400,
                  ),
                ),
              ),
            ),
          ),

          // Video 选项
          Expanded(
            child: GestureDetector(
              onTap: () => viewModel.switchCategory(ContentType.video),
              child: Container(
                height: 56.h,
                decoration: BoxDecoration(
                  color:
                      viewModel.selectedCategory == ContentType.video
                          ? MagmaColor.purple
                          : Colors.transparent,
                  borderRadius: BorderRadius.only(
                    topRight: Radius.circular(28.r),
                    bottomRight: Radius.circular(28.r),
                    topLeft:
                        viewModel.selectedCategory == ContentType.video
                            ? Radius.circular(28.r)
                            : Radius.zero,
                    bottomLeft:
                        viewModel.selectedCategory == ContentType.video
                            ? Radius.circular(28.r)
                            : Radius.zero,
                  ),
                ),
                child: Center(
                  child: Text('Video').blackHanSans(
                    fontSize: 20.sp,
                    color:
                        viewModel.selectedCategory == ContentType.video
                            ? MagmaColor.black
                            : MagmaColor.white,
                    fontWeight: FontWeight.w400,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建标题输入框
  Widget _constructTitleInput(PublishDynamicNavigatorViewModel viewModel) {
    return Container(
      height: 56.h,
      decoration: BoxDecoration(
        border: DashedBorder.all(
          color: MagmaColor.white.withOpacity(0.5),
          width: 1.w,
          dashLength: 6.w,
          spaceLength: 6.w,
        ),
        borderRadius: BorderRadius.circular(8.r),
      ),
      child: TextField(
        controller: viewModel.titleInput,
        style: TextStyle(color: MagmaColor.white, fontSize: 16.sp),
        decoration: InputDecoration(
          border: InputBorder.none,
          contentPadding: EdgeInsets.symmetric(
            horizontal: 16.w,
            vertical: 16.h,
          ),
        ),
      ),
    );
  }

  /// 构建简介输入框
  Widget _constructDescriptionInput(
    PublishDynamicNavigatorViewModel viewModel,
  ) {
    return Container(
      height: 120.h,
      decoration: BoxDecoration(
        border: DashedBorder.all(
          color: MagmaColor.white.withOpacity(0.5),
          width: 1.w,
          dashLength: 6.w,
          spaceLength: 6.w,
        ),
        borderRadius: BorderRadius.circular(8.r),
      ),
      child: TextField(
        controller: viewModel.descriptionInput,
        maxLines: null,
        style: TextStyle(color: MagmaColor.white, fontSize: 16.sp),
        decoration: InputDecoration(
          border: InputBorder.none,
          contentPadding: EdgeInsets.all(16.w),
        ),
      ),
    );
  }

  /// 组装图片选择器
  Widget _assemblePictureSelector(
    BuildContext context,
    PublishDynamicNavigatorViewModel viewModel,
  ) {
    return MagmaTap(
      onTap: () => viewModel.selectMediaResource(context),
      child: Container(
        width: 166.w,
        height: 166.w,
        decoration: BoxDecoration(
          border: DashedBorder.all(
            color: MagmaColor.white.withOpacity(0.5),
            width: 1.w,
            dashLength: 6.w,
            spaceLength: 6.w,
          ),
          borderRadius: BorderRadius.circular(8.r),
        ),
        child:
            viewModel.resourceLocation != null
                ? ClipRRect(
                  borderRadius: BorderRadius.circular(8.r),
                  child:
                      viewModel.selectedCategory == ContentType.image
                          ? Image.file(
                            File(viewModel.resourceLocation!),
                            fit: BoxFit.cover,
                          )
                          : viewModel.thumbnailLocation != null
                          ? Stack(
                            fit: StackFit.expand,
                            children: [
                              Image.file(
                                File(viewModel.thumbnailLocation!),
                                fit: BoxFit.cover,
                              ),
                              Center(
                                child: Container(
                                  width: 48.w,
                                  height: 48.w,
                                  decoration: BoxDecoration(
                                    color: MagmaColor.black.withOpacity(0.6),
                                    shape: BoxShape.circle,
                                  ),
                                  child: Icon(
                                    Icons.play_arrow,
                                    color: MagmaColor.white,
                                    size: 32.w,
                                  ),
                                ),
                              ),
                            ],
                          )
                          : Container(
                            color: MagmaColor.black,
                            child: Center(
                              child: Icon(
                                Icons.videocam,
                                color: MagmaColor.white,
                                size: 48.w,
                              ),
                            ),
                          ),
                )
                : Center(
                  child: Image.asset(
                    MagmaConstant.upload,
                    width: 32.w,
                    height: 32.w,
                  ),
                ),
      ),
    );
  }

  /// 构建发布按钮
  Widget _constructReleaseButton(
    BuildContext context,
    PublishDynamicNavigatorViewModel viewModel,
  ) {
    return MagmaTap(
      onTap: () async {
        // 检查登录
        if (!viewModel.isLoggedIn) {
          await LoginRequiredDialog.show(context);
          return;
        }

        MagmaLoading.show(context);

        // 发布
        final result = await viewModel.releaseContent();

        MagmaLoading.hide();

        if (result) {
          if (!context.mounted) return;
          MagmaToast.success(context, title: 'Published successfully');
          QR.back();
        } else {
          if (!context.mounted) return;
          MagmaToast.error(
            context,
            title: viewModel.modelError ?? 'Failed to publish',
          );
        }
      },
      child: Container(
        width: double.infinity,
        height: 56.h,
        decoration: BoxDecoration(
          color: MagmaColor.purple,
          borderRadius: BorderRadius.circular(28.r),
        ),
        child: Center(
          child: Text('Release').blackHanSans(
            fontSize: 20.sp,
            color: MagmaColor.black,
            fontWeight: FontWeight.w400,
          ),
        ),
      ),
    );
  }

  /// 组装 EULA 链接
  Widget _assembleEulaLink() {
    return MagmaTap(
      onTap: () => MagmaUrl.openUrl(MagmaConstant.eulaUrl),
      child: Center(
        child: Text(
          'EULA',
          style: TextStyle(
            decoration: TextDecoration.underline,
            decorationColor: MagmaColor.white,
            fontSize: 14.sp,
            color: MagmaColor.white,
            fontWeight: FontWeight.w400,
          ),
        ),
      ),
    );
  }
}
